package com.gz.logistics.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gz.logistics.R;
import com.gz.logistics.adapter.GetClothesOrderAdapter;
import com.gz.logistics.adapter.GiveClothesOrderAdapter;
import com.gz.logistics.adapter.SpinnerAdapter;
import com.gz.logistics.app.Define;
import com.gz.logistics.app.MainActivity;
import com.gz.logistics.library.IAuthor;
import com.gz.logistics.library.IOrder;
import com.gz.logistics.library.listener.GetClothesGroupListener;
import com.gz.logistics.library.listener.GetClothesOrderListener;
import com.gz.logistics.library.listener.PostMoneyListener;
import com.gz.logistics.library.listener.PostSignListener;
import com.gz.logistics.library.listener.RequestCode;
import com.gz.logistics.library.pojo.ClothesGroup;
import com.gz.logistics.library.pojo.CustomerSpinnerObject;
import com.gz.logistics.library.pojo.GetClothes;
import com.gz.logistics.library.pojo.OrderStatusInfo;
import com.gz.logistics.library.pojo.UserInfo;
import com.gz.logistics.library.util.Constants;
import com.gz.logistics.library.util.CrashHandler;
import com.gz.logistics.library.util.PreferenceModel;
import com.gz.logistics.util.ToastUtils;
import com.gz.logistics.widget.DoubleDatePickerDialog;
import com.gz.logistics.widget.FooterView;
import com.gz.logistics.widget.LoadingCover;
import com.gz.logistics.widget.SpinerPopWindow;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 洗衣订单列表
 */
public  class HomeFragment extends Fragment implements View.OnClickListener,DoubleDatePickerDialog.OnDateSetListener,LoadingCover.OnLoadingCoverRefreshListener,FooterView.OnFooterViewRefreshListener,
        PullToRefreshBase.OnRefreshListener,GetClothesOrderAdapter.SignALLCallbackInterface,GiveClothesOrderAdapter.SignALLCallbackInterface,GiveClothesOrderAdapter.SignOrderbackInterface{
    private String TAG = HomeFragment.class.getSimpleName();
    private View mConvertView;
    private UserInfo userInfo;
    private Context mContext;
    private List<CustomerSpinnerObject> grouplists;//仓库列表
    private List<CustomerSpinnerObject> statusList;//订单状态列表
    private List<CustomerSpinnerObject> buildings;//楼房列表
    private List<GetClothes> clotheslist;//收衣订单集合
    private List<GetClothes> giveclotheslist;//送还衣物集合
    private OrderStatusInfo statusInfo ;

    private SpinerPopWindow mgroupPopwindow;
    private SpinerPopWindow mStatusSpinnerPopWindow;//状态窗口
    private SpinerPopWindow mbuildingsPopwindow;//楼房窗口

    private SpinnerAdapter statusSpinnerAdapter;
    private SpinnerAdapter mgroupsSpinnerAdapter;
    private SpinnerAdapter mbuildingsSpinnerAdapter;
    private GetClothesOrderAdapter getClothesOrderAdapter;//加载订单列表适配器
    private GiveClothesOrderAdapter giveClothesOrderAdapter;//送还衣物订单适配器
    private RelativeLayout rl_choice_for_order;//小区下拉框
    private RelativeLayout rl_choice_for_building;//单元楼下拉框
    private RelativeLayout rl_choice_for_time;//时间选择
    private RelativeLayout rl_choice_for_status;//订单状态

    private myGetClothesgroups myGetClothesgroupsistener;//查询小区的监听器
    private myGetClothesBuilds myGetClothesbuildinglistener;//查询楼房监听器

    private MyStatusSpinnerItemSelectListener mStatusSpinnerListener;
    private MyClothesGroupOnItemSelectListener clothesGroupOnItemSelectListener;
    private MyBuildSpinnerOnItemSelectListener clothesbuildingOnItemSelectListener;
    private PostMoneyListener postmoneyListener;//收款监听
    private PostSignListener postSignListener;//签收监听
    private DoubleDatePickerDialog timeDialog;
    private Calendar mCalendar;

    private MyHandler mHandler;
    private Dialog mLoadingData;
    private TextView show_tv;
    private LoadingCover mloadCover;
    private FooterView mFooterView;
    private PullToRefreshListView mPullList_getclothes;//预约订单
    private PullToRefreshListView mPullList_giveclothes;//送还衣物订单
    private TextView mTvTitle;
    private RelativeLayout btn_ok;
    private Dialog mMenudialog;

    private TextView getclothes;//预约单收取衣物按钮
    private TextView giveclothes;//送还衣物的按钮

    private View view_line;

    private int page = 1;//分页查询第几页
    public static int user_type = 1;//标识送或者收取衣物（yemian ）
    private int group_id = 0;//小区的id
    private int building_id = 0;//楼房的id
    private String startTime = ""; //开始时间
    private String endTime = "";//结束时间
    public static int status = 2;//订单状态（1.代表已签收 2.代表未签收）
    private RefreshReceiver mRefreshReceiver;
    private String style = "";//用来标识是收取衣物的收款还是送还衣物的收款
    private String order_num = "";//订单编号

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mConvertView == null){
            mConvertView = inflater.inflate(R.layout.fragment_wash,container,false);
            mRefreshReceiver = new RefreshReceiver();
            IntentFilter intentFilter = new IntentFilter(Define.ACTION_REFRESH_CLOTHESLIST);
            getActivity().registerReceiver(mRefreshReceiver, intentFilter);
            init(inflater);
            initListener();
            initSignListener();

        }

        return mConvertView;

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler.release();
        myGetClothesgroupsistener.release();
        clothesGroupOnItemSelectListener.release();
        myGetClothesbuildinglistener.release();
        mStatusSpinnerListener.release();

    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    /**
     * 接收到的广播
     */
    private class RefreshReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            loadDataFromServer(buildListener(RequestCode.PULL));
        }
    }
    /**
     * 各种界面控件的点击事件
     * @param view
     */
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.rl_choice_for_order:
                if (grouplists.size() <= 0){
                    ToastUtils.showToast(this.getActivity(),"小区列表为空");
                }
                mgroupPopwindow.setWidth(rl_choice_for_order.getWidth());
                mgroupPopwindow.showAsDropDown(rl_choice_for_order);
                break;
            case R.id.rl_choice_for_time:
                timeDialog.show();
                break;
            case R.id.getclothes://点击预约订单
                user_type = 1;
                status = 2;
                reSetGroupList();
                reSetBuildingList();
                reSetstatusList();
                view_line.setVisibility(View.GONE);
                rl_choice_for_time.setVisibility(View.GONE);
                getclothes.setBackgroundResource(R.drawable.bg_my_orders_frame_orange);
                getclothes.setTextColor(getResources().getColor(R.color.RGB_ff8018));
                giveclothes.setBackgroundResource(R.drawable.bg_my_orders_frame_gray);
                giveclothes.setTextColor(getResources().getColor(R.color.RGB_666666));
                mPullList_getclothes.setVisibility(View.VISIBLE);
                mPullList_giveclothes.setVisibility(View.GONE);
                loadDataFromServer(buildListener(RequestCode.PULL));
                break;
            case R.id.giveclothes:
                user_type = 2;
                status = 2;
                reSetGroupList();
                reSetBuildingList();
                reSetstatusList();
                view_line.setVisibility(View.VISIBLE);
                rl_choice_for_time.setVisibility(View.VISIBLE);
                getclothes.setBackgroundResource(R.drawable.bg_my_orders_frame_gray);
                getclothes.setTextColor(getResources().getColor(R.color.RGB_666666));
                giveclothes.setBackgroundResource(R.drawable.bg_my_orders_frame_orange);
                giveclothes.setTextColor(getResources().getColor(R.color.RGB_ff8018));
                mPullList_getclothes.setVisibility(View.GONE);
                mPullList_giveclothes.setVisibility(View.VISIBLE);
                loadDataFromServer(buildListener(RequestCode.PULL));
                break;
            case R.id.rl_choice_for_building:
                if (buildings.size() <= 0){
                    ToastUtils.showToast(this.getActivity(),"楼房列表为空");
                }
                mbuildingsPopwindow.setWidth(rl_choice_for_building.getWidth());
                mbuildingsPopwindow.showAsDropDown(rl_choice_for_building);
                break;
            case R.id.rl_choice_for_status:
                if (statusList.size() <= 0){
                    ToastUtils.showToast(getActivity(),"状态列表为空");
                    return;
                }
                mStatusSpinnerPopWindow.setWidth(rl_choice_for_status.getWidth());
                mStatusSpinnerPopWindow.showAsDropDown(rl_choice_for_status);
                break;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Define.ACTIVITY_CODE_ORDER_DETAIL && resultCode == Define.ACTIVITY_CODE_ORDER_DETAI_CHANGE){
            if (data != null){

            }
        }

    }
    /**
     *     初始化控件
     */
    private void init(LayoutInflater mInflater) {
        mContext = getActivity().getApplicationContext();
        userInfo = IAuthor.getInstance().loadUserInfoSyn(PreferenceModel.getInt(Constants.PREFERENCE_USER_ID, -1));

        rl_choice_for_order = (RelativeLayout) mConvertView.findViewById(R.id.rl_choice_for_order);//小区选择
        rl_choice_for_order.setOnClickListener(this);
        rl_choice_for_time = (RelativeLayout) mConvertView.findViewById(R.id.rl_choice_for_time);//时间段选择
        rl_choice_for_time.setOnClickListener(this);
        rl_choice_for_building = (RelativeLayout) mConvertView.findViewById(R.id.rl_choice_for_building);//单元楼选择
        rl_choice_for_building.setOnClickListener(this);
        rl_choice_for_status = (RelativeLayout) mConvertView.findViewById(R.id.rl_choice_for_status);//订单装填选择
        rl_choice_for_status.setOnClickListener(this);
        getclothes = (TextView) mConvertView.findViewById(R.id.getclothes);//预约订单按钮
        getclothes.setOnClickListener(this);
        giveclothes = (TextView) mConvertView.findViewById(R.id.giveclothes);//送还衣物按钮
        giveclothes.setOnClickListener(this);
        view_line = (View) mConvertView.findViewById(R.id.view);
        view_line.setVisibility(View.GONE);
        rl_choice_for_time.setVisibility(View.GONE);
        mHandler = new MyHandler(this);

        mPullList_getclothes = (PullToRefreshListView) mConvertView.findViewById(R.id.list1);//预约接单
        mPullList_getclothes.setVisibility(View.VISIBLE);
        mPullList_giveclothes = (PullToRefreshListView) mConvertView.findViewById(R.id.list2);//送还衣物
        mPullList_giveclothes.setVisibility(View.GONE);
        mloadCover = (LoadingCover) mConvertView.findViewById(R.id.layout_loading_cover);
        mloadCover.setOnLoadingCoverRefreshListener(this);

        mLoadingData = new Dialog(getActivity(),R.style.DialogTheme);
        mLoadingData.setContentView(R.layout.loading_data_dialog2);
        mLoadingData.setCanceledOnTouchOutside(false);
        mLoadingData.setCancelable(false);
        show_tv = (TextView)mLoadingData.findViewById(R.id.show_tv);

        mFooterView = (FooterView) mInflater.inflate(R.layout.footer_view, null);
        mPullList_getclothes.getRefreshableView().addFooterView(mFooterView);
        mPullList_getclothes.setOnScrollListener(mFooterView);
        mPullList_getclothes.setOnRefreshListener(this);
        mPullList_giveclothes.getRefreshableView().addFooterView(mFooterView);
        mPullList_giveclothes.setOnScrollListener(mFooterView);
        mPullList_giveclothes.setOnRefreshListener(this);

        mFooterView.setOnFooterViewRefreshListener(this);
        mloadCover.setOnLoadingCoverRefreshListener(this);

        statusList = new ArrayList<CustomerSpinnerObject>();
        grouplists = new ArrayList<CustomerSpinnerObject>();
        buildings = new ArrayList<CustomerSpinnerObject>();
        clotheslist = new ArrayList<GetClothes>();
        giveclotheslist = new ArrayList<GetClothes>();

        myGetClothesgroupsistener = new myGetClothesgroups(this);
        myGetClothesbuildinglistener = new myGetClothesBuilds(this);

        for(int i = 1 ; i <= 2 ;i++){
            statusInfo = new OrderStatusInfo();
            if (i == 1 ){
                statusInfo.setStatus_id(Define.ORDER_STATUS_LOGISTIC_SIGNED);
                statusInfo.setStatus_name("已签收");
            }else if (i == 2 ){
                statusInfo.setStatus_id(Define.ORDER_STATUS_LOGISTIC_NOT_SIGN);
                statusInfo.setStatus_name("待签收");
                statusInfo.setIsSelected(true);
            }
            statusList.add(statusInfo);
        }
        statusSpinnerAdapter = new SpinnerAdapter(this.getActivity(),statusList);
        mStatusSpinnerPopWindow = new SpinerPopWindow(this.getActivity());
        mStatusSpinnerPopWindow.setAdatper(statusSpinnerAdapter);
        mStatusSpinnerListener = new MyStatusSpinnerItemSelectListener(this);
        mStatusSpinnerPopWindow.setItemListener(mStatusSpinnerListener);

        mgroupsSpinnerAdapter = new SpinnerAdapter(this.getActivity(),grouplists);
        mgroupPopwindow = new SpinerPopWindow(this.getActivity());
        mgroupPopwindow.setAdatper(mgroupsSpinnerAdapter);
        clothesGroupOnItemSelectListener = new MyClothesGroupOnItemSelectListener(this);
        mgroupPopwindow.setItemListener(clothesGroupOnItemSelectListener);

        mbuildingsSpinnerAdapter = new SpinnerAdapter(this.getActivity(),buildings);
        mbuildingsPopwindow = new SpinerPopWindow(this.getActivity());
        mbuildingsPopwindow.setAdatper(mbuildingsSpinnerAdapter);
        clothesbuildingOnItemSelectListener = new MyBuildSpinnerOnItemSelectListener(this);
        mbuildingsPopwindow.setItemListener(clothesbuildingOnItemSelectListener);

        getClothesOrderAdapter = new GetClothesOrderAdapter(clotheslist,mContext,this);
        giveClothesOrderAdapter = new GiveClothesOrderAdapter(giveclotheslist,mContext,this,this);
        mPullList_getclothes.setAdapter(getClothesOrderAdapter);
        mPullList_giveclothes.setAdapter(giveClothesOrderAdapter);
        mHandler.sendEmptyMessage(1);
        mCalendar = Calendar.getInstance();
        timeDialog = new DoubleDatePickerDialog(this.getActivity(),0,this,mCalendar.get(Calendar.YEAR),mCalendar.get(Calendar.MONTH),mCalendar.get(Calendar.DATE),true);

        user_type = 1;//默认的user_type等于1
        loadDataFromServer(buildListener(RequestCode.PULL));

    }
    /**
     *  弹出时间选择 Dialog，并选择对应开始和介素时间后，点击确定按钮，将会触发以下方法
     *
     */
    @Override
    public void onDateSet(DatePicker startDatePicker, int startYear, int startMonthOfYear, int startDayOfMonth, DatePicker endDatePicker, int endYear, int endMonthOfYear, int endDayOfMonth) {
        startTime = String.format("%d-%d-%d",startYear,startMonthOfYear+1,startDayOfMonth)+" 00:00:00";
        endTime = String.format("%d-%d-%d",endYear,endMonthOfYear+1,endDayOfMonth)+" 23:59:59";
        CrashHandler.i(TAG, "开始时间=" + startTime + "结束时间=" + endTime);
        mLoadingData.show();
        loadDataFromServer(buildListener(RequestCode.PULL));
    }
    public static class MyHandler extends android.os.Handler{
        private HomeFragment mOuter;

        public MyHandler(HomeFragment mOuter) {
            this.mOuter = mOuter;
        }
        public void release(){
            new WeakReference<HomeFragment>(mOuter);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    IOrder.getInstance().getClothesCommunity(user_type, mOuter.myGetClothesgroupsistener);
                    break;
            }
        }
    }

    private void loadDataFromServer(GetClothesOrderListener getClothesOrderListener) {
        if (user_type==1){
            mPullList_getclothes.setVisibility(View.VISIBLE);
            mPullList_giveclothes.setVisibility(View.GONE);
        }else{
            mPullList_giveclothes.setVisibility(View.VISIBLE);
            mPullList_getclothes.setVisibility(View.GONE);
        }

        if(getClothesOrderListener.getRequestCode() == RequestCode.PULL) {
            page = 1;
        }else if(getClothesOrderListener.getRequestCode() == RequestCode.SCROLL) {
            page++;
        }
        IOrder.getInstance().getClothesOrders(group_id,building_id,status,user_type,page,startTime,endTime, getClothesOrderListener);

    }
    @Override
    public void onFooterViewRefresh() {
        loadDataFromServer(buildListener(RequestCode.SCROLL));
    }

    @Override
    public void onRefresh(PullToRefreshBase refreshView) {
        loadDataFromServer(buildListener(RequestCode.PULL));
    }

    @Override
    public void onLoadingCoverRefresh() {
        loadDataFromServer(buildListener(RequestCode.PULL));

    }
    /**
     * 状态
     */
    public static class MyStatusSpinnerItemSelectListener implements SpinerPopWindow.ISpinnerOnItemSelectListener {
        private HomeFragment mOuter;

        public MyStatusSpinnerItemSelectListener(HomeFragment mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<HomeFragment>(mOuter);
        }
        @Override
        public void onSpinnerItemClick(int position) {
            mOuter.mLoadingData.show();
            mOuter.page = 1;
            mOuter.status = ((OrderStatusInfo)mOuter.statusList.get(position)).getStatus_id();

            for(int j = 0 ; j < mOuter.statusList.size() ; j++){ // 把选中的状态置为选中状态，
                if(j == position){
                    (mOuter.statusList.get(j)).setIsSelected(true);
                }else{
                    (mOuter.statusList.get(j)).setIsSelected(false);
                }
            }
            if(user_type ==1){
                mOuter.clotheslist.clear();
                mOuter.getClothesOrderAdapter.notifyDataSetChanged();
            }else{
                mOuter.giveclotheslist.clear();
                mOuter.giveClothesOrderAdapter.notifyDataSetChanged();
            }
            mOuter.loadDataFromServer(mOuter.buildListener(RequestCode.PULL));

        }
    }

    /**
     * 获取小区列表
     */
    public static class myGetClothesgroups extends GetClothesGroupListener {
        private HomeFragment mOuter;

        public myGetClothesgroups(HomeFragment mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<HomeFragment>(mOuter);
        }

        @Override
        public void onResponseSuccess(List<ClothesGroup> grouplist) {
            ClothesGroup groupinfo = new ClothesGroup();
            groupinfo.setId(0);
            groupinfo.setGroupname("全部");
            groupinfo.setIsSelected(true);
            grouplist.add(0, groupinfo);
            mOuter.grouplists.clear();
            mOuter.grouplists.addAll(grouplist);
        }
        @Override
        public void onNoMoreData() {

        }
        @Override
        public void onResponseFailed() {

        }
    }

    /**
     * 获取小区列表
     */
    public static class myGetClothesBuilds extends GetClothesGroupListener {
        private HomeFragment mOuter;

        public myGetClothesBuilds(HomeFragment mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<HomeFragment>(mOuter);
        }

        @Override
        public void onResponseSuccess(List<ClothesGroup> grouplist) {
            mOuter.mLoadingData.dismiss();
            ClothesGroup buildinginfo = new ClothesGroup();
            buildinginfo.setId(0);
            buildinginfo.setGroupname("全部");
            buildinginfo.setIsSelected(true);
            grouplist.add(0, buildinginfo);
            mOuter.buildings.clear();
            mOuter.buildings.addAll(grouplist);
        }
        @Override
        public void onNoMoreData() {

        }
        @Override
        public void onResponseFailed() {

        }
    }
    /**
     *小区下拉列表的 item 点击事件监听器
     * 杜志娟 2016-03-14
     */
    public static class MyClothesGroupOnItemSelectListener implements SpinerPopWindow.ISpinnerOnItemSelectListener {
        private HomeFragment mOuter;

        public MyClothesGroupOnItemSelectListener(HomeFragment mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<HomeFragment>(mOuter);
        }
        @Override
        public void onSpinnerItemClick(int position) {
            mOuter.mLoadingData.show();
            mOuter.group_id = ((ClothesGroup)mOuter.grouplists.get(position)).getId();
            for(int j = 0 ; j < mOuter.grouplists.size() ; j++){ // 把选中的仓库置为选中状态，
                if(j == position){
                    (mOuter.grouplists.get(j)).setIsSelected(true);
                    if (((ClothesGroup)mOuter.grouplists.get(position)).getId()==0){
                        mOuter.buildings.clear();
                        mOuter.mbuildingsSpinnerAdapter.notifyDataSetChanged();
                    }else{
                        //调用查询其下的小区的接口
                        IOrder.getInstance().getClothesBuildings(mOuter.group_id,user_type, mOuter.myGetClothesbuildinglistener);
                    }

                }else{
                    (mOuter.grouplists.get(j)).setIsSelected(false);
                }
            }

        }
    }
    /**
     *楼房下拉列表的 item 点击事件监听器
     * 杜志娟 2016-03-14
     */
    public static class MyBuildSpinnerOnItemSelectListener implements SpinerPopWindow.ISpinnerOnItemSelectListener {
        private HomeFragment mOuter;

        public MyBuildSpinnerOnItemSelectListener(HomeFragment mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<HomeFragment>(mOuter);
        }
        @Override
        public void onSpinnerItemClick(int position) {
            mOuter.mLoadingData.show();
            mOuter.building_id = ((ClothesGroup)mOuter.buildings.get(position)).getId();
            for(int j = 0 ; j < mOuter.buildings.size() ; j++){ // 把选中的仓库置为选中状态，
                if(j == position){
                    (mOuter.buildings.get(j)).setIsSelected(true);
                     mOuter.loadDataFromServer(mOuter.buildListener(RequestCode.PULL));
                }else{
                    (mOuter.buildings.get(j)).setIsSelected(false);
                }
            }

        }
    }
    private GetClothesOrderListener buildListener(RequestCode requestCode) {
        return new GetClothesOrderListener(requestCode) {
            @Override
            public void onResponseFailed() {
                // TODO Auto-generated method stub
                mloadCover.onRefreshFailed();
                mFooterView.onRefreshFailed();
                if (user_type==1){
                    if (mPullList_getclothes.isRefreshing()) {
                        mPullList_getclothes.getLoadingLayoutProxy().refreshFailed();
                    }
                }else{
                    if (mPullList_giveclothes.isRefreshing()) {
                        mPullList_giveclothes.getLoadingLayoutProxy().refreshFailed();
                    }
                }
                if(mLoadingData.isShowing()){
                    mLoadingData.dismiss();
                }
            }

            @Override
            public void onOffline() {
                // TODO Auto-generated method stub
                mloadCover.onRefreshFailed(Define.MSG_OFFLINE_ERROR);
                if (user_type==1){
                    if (mPullList_getclothes.isRefreshing()) {
                        mPullList_getclothes.getLoadingLayoutProxy().refreshFailed();
                    }
                }else{
                    if (mPullList_giveclothes.isRefreshing()) {
                        mPullList_giveclothes.getLoadingLayoutProxy().refreshFailed();
                    }
                }
                if(mLoadingData.isShowing()){
                    mLoadingData.dismiss();
                }
            }

            @Override
            public void onNoNetWork() {
                // TODO Auto-generated method stub
                if (user_type==1){
                    if (mPullList_getclothes.isRefreshing()) {
                        mPullList_getclothes.getLoadingLayoutProxy().refreshFailed();
                    }
                }else{
                    if (mPullList_giveclothes.isRefreshing()) {
                        mPullList_giveclothes.getLoadingLayoutProxy().refreshFailed();
                    }
                }
                if(mLoadingData.isShowing()){
                    mLoadingData.dismiss();
                }
                mFooterView.onRefreshFailed();
                mloadCover.onRefreshFailed(Define.MSG_NO_NETWORK);
            }

            @Override
            public void onNoMoreData() {
                // TODO Auto-generated method stub
                if (user_type==1){
                    if (mPullList_getclothes.isRefreshing()) {
                        mPullList_getclothes.getLoadingLayoutProxy().refreshSuccess();
                    }
                }else{
                    if (mPullList_giveclothes.isRefreshing()) {
                        mPullList_giveclothes.getLoadingLayoutProxy().refreshSuccess();
                    }
                }
                if(mLoadingData.isShowing()){
                    mLoadingData.dismiss();
                }
                getClothesOrderAdapter.notifyDataSetChanged();
                giveClothesOrderAdapter.notifyDataSetChanged();
                mFooterView.onRefreshComplete();
                mloadCover.onRefreshFailed("暂无订单信息");

            }

            @Override
            public void onResponseSuccess(List<GetClothes> lists) {

                if (this.requestCode == RequestCode.PULL) {
                    clotheslist.clear();
                    giveclotheslist.clear();
                }
                if (user_type==1){
                    clotheslist.addAll(lists);
                    getClothesOrderAdapter.notifyDataSetChanged();
                }else if (user_type==2){
                    giveclotheslist.addAll(lists);
                    giveClothesOrderAdapter.notifyDataSetChanged();
                }

                if (lists.size() < Define.LISTVIEW_ITEM_MIN_SIZE) {
                    mFooterView.onRefreshComplete();
                    mPullList_getclothes.setOnScrollListener(null);
                    mPullList_giveclothes.setOnScrollListener(null);

                } else {
                    getClothesOrderAdapter.notifyDataSetChanged();
                    giveClothesOrderAdapter.notifyDataSetChanged();
                    mFooterView.onRefreshSuccess();//刷新成功并且后面还有数据可以进行加载
                    mPullList_getclothes.setOnScrollListener(mFooterView);
                    mPullList_giveclothes.setOnScrollListener(mFooterView);
                }
                if (user_type==1){
                    if (mPullList_getclothes.isRefreshing()) {
                        mPullList_getclothes.getLoadingLayoutProxy().refreshSuccess();
                    }
                }else{
                    if (mPullList_giveclothes.isRefreshing()) {
                        mPullList_giveclothes.getLoadingLayoutProxy().refreshSuccess();
                    }
                }

                if(mLoadingData.isShowing()){
                    mLoadingData.dismiss();
                }
                mloadCover.onRefreshSuccess();
            }
        };
    }

    public void createDialog(final String order_num,double money,String style) {
        mMenudialog = new Dialog(MainActivity.context, R.style.DialogTheme);
        View dialogView = LayoutInflater.from(MainActivity.context).inflate(R.layout.mycommunity_dialog_layout, null);
        mTvTitle = (TextView) dialogView.findViewById(R.id.tv_title);
        if (money>0){
            mTvTitle.setText("应收取金额：");
        }else{
            mTvTitle.setText("应退还金额：");
        }
        this.style = style;
        this.order_num = order_num;
        final EditText edittext = (EditText) dialogView.findViewById(R.id.money);
        edittext.setText(money+"");
        btn_ok = (RelativeLayout) dialogView.findViewById(R.id.btn_ok);
        btn_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                show_tv.setText("提交中...");
                mLoadingData.show();
                IOrder.getInstance().PostReceipt(user_type,order_num, edittext.getText().toString().trim(), postmoneyListener);
                mMenudialog.dismiss();
            }
        });
        dialogView.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mMenudialog.dismiss();
            }
        });
        mMenudialog.setContentView(dialogView);
        mMenudialog.setCancelable(false);
        mMenudialog.setCanceledOnTouchOutside(false);
        mMenudialog.show();
    }

    private void initListener() {

        postmoneyListener = new PostMoneyListener() {

            @Override
            public void onResponseSuccess() {
                ToastUtils.showToast(getActivity(), "收款成功！", Toast.LENGTH_SHORT);
                mLoadingData.dismiss();
                if (style.equals("收取")){
                    loadDataFromServer(buildListener(RequestCode.PULL));
                }else{
                    signOrder(order_num);
                }

            }

            @Override
            public void onOffline() {//处于离线状态
                // TODO Auto-generated method stub
                mLoadingData.dismiss();
            }

            @Override
            public void onResponseFailed() {
                ToastUtils.showToast(getActivity(), "收款失败,请重试", Toast.LENGTH_SHORT);
                mLoadingData.dismiss();
            }

            @Override
            public void onNoMoreData() {
                ToastUtils.showToast(getActivity(), "订单号为空");
                mLoadingData.dismiss();
            }

            @Override
            public void onNoNetWork() {//没有任何网络连接
                // TODO Auto-generated method stub
                ToastUtils.showToast(getActivity(), "收款类型为空");
                mLoadingData.dismiss();
            }
        };

    }

    /**
     * 收款
     * @param order_no
     */
    public void signAll(String order_no,double money,String style) {
        createDialog(order_no,money,style);
    }

    /**
     * 签收
     * @param order_no
     */
    public void signOrder(String order_no) {
        mLoadingData.show();
        IOrder.getInstance().PostSign(order_no,postSignListener);
    }
    /**
     * 恢复小区默认第一个未选中
     */
    public void reSetGroupList(){
        group_id = 0;
        for (CustomerSpinnerObject  object : grouplists){
            if(((ClothesGroup)object).getId() == 0){
                object.setIsSelected(true);
            }else{
                object.setIsSelected(false);
            }

        }
    }
    /**
     * 恢复楼宇的选项
     */
    public void reSetBuildingList(){
        building_id = 0;
        for (CustomerSpinnerObject  object : buildings){
            if(((ClothesGroup)object).getId() == 0){
                object.setIsSelected(true);
            }else{
                object.setIsSelected(false);
            }

        }
    }
    /**
     * 恢复状态的选项
     */
    public void reSetstatusList(){
        status = 2;
        for (CustomerSpinnerObject  object : statusList){
            if(((OrderStatusInfo)object).getStatus_id() == 2){
                object.setIsSelected(true);
                return;
            }else{
                object.setIsSelected(false);
            }

        }
    }
    private void initSignListener() {

        postSignListener = new PostSignListener() {

            @Override
            public void onResponseSuccess() {
                ToastUtils.showToast(mContext, "签收成功！", Toast.LENGTH_SHORT);
                status = 1;
                for (CustomerSpinnerObject  object : statusList){
                    if(((OrderStatusInfo)object).getStatus_id() == 1){
                        object.setIsSelected(true);
                    }else{
                        object.setIsSelected(false);
                    }

                }
                loadDataFromServer(buildListener(RequestCode.PULL));
                mLoadingData.dismiss();
            }

            @Override
            public void onOffline() {//处于离线状态
                // TODO Auto-generated method stub
                mLoadingData.dismiss();
            }

            @Override
            public void onResponseFailed() {
                ToastUtils.showToast(getActivity(), "签收失败,请重试", Toast.LENGTH_SHORT);
                mLoadingData.dismiss();
            }

            @Override
            public void onNoMoreData() {
                ToastUtils.showToast(getActivity(), "订单号为空");
                mLoadingData.dismiss();
            }

            @Override
            public void onNoNetWork() {//没有任何网络连接
                // TODO Auto-generated method stub
                ToastUtils.showToast(getActivity(), "物流员id为空");
                mLoadingData.dismiss();
            }
        };

    }
}
